<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use PDO;
use Think\Exception;
use wxpay\wxpay;
use alipay\Alipay;
use epay\epay;
use app\admin\model\card\Code as CardCodeModel;
use app\admin\model\card\Log as CardLogModel;
use app\admin\model\agent\Log as AgentLogModel;
use app\admin\model\agent\Setting as AgentSettingModel;
use app\admin\model\agent\Order as AgentOrderModel;
use app\admin\model\Withdrawlapply as WithdrawlapplyModel;
use app\common\model\MoneyLog as UserMoneyLog;
use app\common\model\User as UserModel;
use app\admin\model\reward\Log as RewardLogModel;
use app\admin\model\with\Setting as SettingModel;
use think\Request;
use app\admin\model\agent\Agreement as AgentAgreementModel;

class Agent extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = ['payAgentOrderNotify','getAgentMoney'];
    
    public function getAgerment()
    {
        $data = AgentAgreementModel::field('content')->find();
        $this->success('获取成功',$data);
    }
    
    
    public function agentLogin()
    {
        if($this->auth->is_agent == 0)
        {
            $this->error('非代理，无法登录');
        }
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->agentLogin($account, $password);
        if ($ret) {
            $this->success(__('登录成功'), []);
        } else {
            $this->error($this->auth->getError());
        }
    }
    
    public function getAgentInfo()
    {
        if($this->auth->is_agent == 0)
        {
            //$this->error('非代理，无法登录');
        }
        $data['money'] = $this->auth->money;
        $data['total_money'] = $this->auth->total_money;
        $data['avatar'] = $this->auth->avatar;
        $data['username'] = $this->auth->username;
        //获取旅游卡数量
        $card_where['agent_id']  = $this->auth->id;
        $data['total_card_count'] = CardCodeModel::where($card_where)->count();
        //获取待激活数量
        $card_where['is_exchange']  = '0';
        $data['unuse_card_count'] = CardCodeModel::where($card_where)->count();
        $setting_info = AgentSettingModel::find();
        $data['open_money'] = $setting_info['price'];; 
        $this->success(__('获取成功'), $data);
    }
    
     public function getAgentMoney()
    {
        $setting_info = AgentSettingModel::find();
        $data['open_money'] = $setting_info['price'];; 
        $this->success(__('获取成功'), $data);
    }
    
    public function withSetting()
    {
        $info = SettingModel::find();
        $this->success(__('获取成功'), $info);
    }
    
    public function applyMoney()
    {
        if($this->auth->is_agent == 0)
        {
            $this->error('非代理，无法登录');
        }
        //获取金额
        $money = $this->request->post('money', 0);
        if($money == 0)
        {
            $this->error('请输入提现金额');
        }
        $image = $this->request->post('image', '');
        if(!$image)
        {
            $this->error('请上传收款码');
        }
        if($money > $this->auth->money)
        {
            $this->error("余额不足");
        }
        $rate = config('site.rate');
        $user_data['money'] = $this->auth->money - $money;
        $apply_log['user_id'] = $this->auth->id;
        $apply_log['total_money'] = $money;
        $apply_log['service_money'] = round($money*$rate/100,2);
        $apply_log['money'] = round($apply_log['total_money']-$apply_log['service_money'] ,2);
        $apply_log['create_time'] = time();
        $apply_log['image'] = $image;
        
        Db::startTrans();
        try{
            $user_status = UserModel::where('id',$this->auth->id)->update($user_data);
            $apply_status = WithdrawlapplyModel::insertGetId($apply_log);
            
            $moneey_log = [
                'user_id'=>$this->auth->id,
                'before'=>$this->auth->money,
                'after'=>$user_data['money'],
                'money'=>$money,
                'memo'=>'用户提现',
                'createtime'=>time()
            ];
            UserMoneyLog::insert($moneey_log);
            if($user_status===false || !$apply_status)
            {
                Db::rollback();
                $this->error("提现失败");
            }
        }catch (Exception $exception)
        {
            Db::rollback();
            $this->error("提现失败");
        }
        Db::commit();
        $this->success("提现成功,等待后台工作人员审核");
    }
    
    /**
     * 日志
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function applyLog()
    {
        $page = $this->request->post('page',1);
        $start = 0;
        if($page > 1)
        {
            $start = ($page - 1)*15;
            $this->error("请选择要申请划拨的用户");
        }
        $where['user_id'] = $this->auth->id;
        $list = WithdrawlapplyModel::where($where)->field("create_time,total_money,state,money")->order('apply_id desc')->limit($start,65)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                if($v['state'] == '0')
                {
                    $text = '等待审核';
                }elseif($v['state'] == '1')
                {
                    $text = '审核成功';
                }else
                {
                    $text = '审核失败';
                }

                $list[$k]['status'] =$text;
                $list[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            $this->success('获取成功',$list);
        }
        $this->error('暂无记录');
    }
    
        
    public function getGrouptInfo()
    {
        if($this->auth->is_agent == 0)
        {
            $this->error('获取失败',[]);
        }
        $where['agent_id'] = $this->auth->id;
        //获取团队信息
        $wheres['tagent_id'] = $this->auth->id;
        $return['o_a_count'] = AgentLogModel::where($where)->count();
        $return['t_a_count'] = AgentLogModel::where($wheres)->count();
        $return['a_count'] = $return['o_a_count'] + $return['t_a_count'];
        $return['o_c_count'] = CardLogModel::where($where)->count();
        $return['t_c_count'] = CardLogModel::where($wheres)->count();
        $return['c_count'] = $return['o_c_count'] + $return['t_c_count'];
        $this->success('获取成功',$return);
    }
    
    
    public function vipUserList()
    {
        
        if($this->auth->is_agent == 0)
        {
            $this->error('获取失败',[]);
        }
        $where = [];
        $where['a.agent_id|a.tagent_id'] = $this->auth->id;
        $page = $this->request->post("page",1);
        $start = 0;
        if($page > 1)
        {
           $start = ($page - 1)*15;
        }
        $list = CardLogModel::alias("a")->join("user b","a.user_id = b.id",'left')->join("card_code c","a.user_id = c.user_id",'left')->field("a.*,b.nickname,b.avatar,c.card")->where($where)->order('createtime desc')->limit($start,65)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['lvel'] = '二级';
                if($v['agent_id'] == $this->auth->id)
                {
                    $list[$k]['lvel'] = '一级';
                }
                $list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                //获取金额
                $wheres['user_id'] = $v['user_id'];
                $wheres['type'] = 1;
                $wheres['agent_id'] = $this->auth->id;
                
                $money = RewardLogModel::where($wheres)->value('money');
                $list[$k]['money'] = $money?$money:0;
            }
        }
        $this->success('获取成功',$list);
    }
    
     public function groupUserList()
    {
        if($this->auth->is_agent == 0)
        {
            $this->error('获取失败',[]);
        }
        $where = [];
        $where['agent_id|tagent_id'] = $this->auth->id;
        $page = $this->request->post("page",1);
        $start = 0;
        if($page > 1)
        {
           $start = ($page - 1)*15;
        }
        $list = AgentLogModel::alias("a")->join("user b","a.user_id = b.id",'left')->field("a.*,b.nickname,b.avatar")->where($where)->order('createtime desc')->limit($start,65)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                $list[$k]['lvel'] = '二级';
                if($v['agent_id'] == $this->auth->id)
                {
                    $list[$k]['lvel'] = '一级';
                }
                $wheres['user_id'] = $v['user_id'];
                $wheres['agent_id'] = $this->auth->id;
                $wheres['type'] = 2;
                $money = RewardLogModel::where($wheres)->value('money');
                $list[$k]['money'] = $money?$money:0;
            }
        }
        $this->success('获取成功',$list);
    }
    
    public function getRewardInfo()
    {
        //获取以获取
        $where['agent_id'] = $this->auth->id;
        $where['status'] = '2';
        $return['get_money'] = RewardLogModel::where($where)->sum('money');
        //获取在路上
        $where['status'] = '1';
        $return['wait_money'] = RewardLogModel::where($where)->sum('money');
        
        //获取以体现
        $with_where['state'] = ['<',2];
        $with_where['user_id'] = $this->auth->id;
        $return['with_money'] = WithdrawlapplyModel::where($with_where)->sum('total_money');
        $return['code'] = $this->auth->invite_code;
        $this->success('获取成功',$return);
    }
    
    public function getRewardLogList()
    {
        if($this->auth->is_agent == 0)
        {
            $this->error('获取失败',[]);
        }
        $where = [];
        $where['agent_id'] = $this->auth->id;
        $page = $this->request->post("page",1);
        $start = 0;
        if($page > 1)
        {
           $start = ($page - 1)*15;
        }
        $list = RewardLogModel::alias("a")->join("user b","a.user_id = b.id",'left')->field("a.*,b.nickname,b.avatar")->where($where)->order('createtime desc')->limit($start,65)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                $list[$k]['status'] = '已到账';
                if($v['status'] == '1')
                {
                    $list[$k]['lvel'] = '未到账';
                }
            }
        }
        $this->success('获取成功',$list);
    }
    

    public function createAgentOrder()
    {
        $code = $this->request->post("code",'');
        if($code == '')
        {
            $this->error('网络错误，请重试',[]);
        }
        $username = $this->request->post("username",'');
        if($username == '')
        {
            $this->error('请输入用户名，请重试',[]);
        }
        $password = $this->request->post("password",'');
        if($password == '')
        {
            $this->error('请输入密码，请重试',[]);
        }
        if($this->auth->is_agent == 1)
        {
            //$this->error('您已是代理身份',[]);
        }
        //获取邀请吗是否存在
        $user_info = UserModel::where('invite_code',$code)->find();
        if(!$user_info)
        {
            $this->error('网络错误，请重试',[]);
        }
        $o_user_id = $user_info['id'];
        $t_user_id = 0;
        //获取上级
        $agent_info = AgentLogModel::where('user_id',$user_info['id'])->find();
        if($agent_info && $agent_info['agent_id'])
        {
            $t_user_id = $agent_info['agent_id'];
        }
        //获取金额
        $setting_info = AgentSettingModel::find();
        if(!$setting_info)
        {
            $this->error('网络错误，请重试',[]);
        }
        //$setting_info['price'] = 0.01;
        $ooid = 'A' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $order_data = [
            'user_id'=>$this->auth->id,
            'price'=>$setting_info['price'],
            'zt_money'=>$setting_info['one_price'],
            'jt_money'=>$setting_info['two_price'],
            'out_trade_no'=>$ooid,
            'zt_user_id'=>$o_user_id,
            'jt_user_id'=>$t_user_id,
            'create_time'=>time(),
            'username'=>$username,
            'password'=>$password,
        ];
        $status = AgentOrderModel::insertGetId($order_data);
        if($status)
        {
            $return['order_no'] = $ooid;
            $return['price'] = $setting_info['price'];
            $this->success('去支付',$return);
        }
        $this->error('网络错误，请重试',[]);
    }
    
    public function payAgentOrder()
    {
        $order_no = $this->request->post("order_no",'');
        if($order_no == '')
        {
            $this->error('支付订单信息错误，请重试',[]);
        }
        $order_where['out_trade_no'] = $order_no;
        $order_where['user_id'] = $this->auth->id;
        $order_info = AgentOrderModel::where($order_where)->find();
        if(!$order_info)
        {
            $this->error('支付订单信息错误，请重试',[]);
        }
        if($order_info['status'] == 1)
        {
            $this->error('您已支付');
        }
        $title = '升级成为代理';
        $Wxpay = new \app\admin\library\Wxpay();
        $url = 'https://travel.fastwork.vip/';
        $res = $Wxpay->wxPay($order_no,$order_info['price'],$title,$url.'/api/agent/payAgentOrderNotify','jsapi',$this->auth->wx_mini_openid);
        if($res['code'] == 1)
        {
            $this->success("获取成功",$res['data']);
        }
        $this->error("支付失败",[]);
    }
    
    public function payAgentOrderNotify()
    {
        
        $header = Request::instance()->header();
        $inWechatpaySignature = $header['wechatpay-signature'];
        $inWechatpayTimestamp = $header['wechatpay-timestamp'];
        $inWechatpaySerial = $header['wechatpay-serial'];
        $inWechatpayNonce = $header['wechatpay-nonce'];

        $Wxpay = new \app\admin\library\Wxpay();
        if (!$inWechatpaySignature or !$inWechatpayTimestamp or !$inWechatpaySerial or !$inWechatpayNonce) {
            header("Location:/404.html");
            exit;
        }
        $inBody = file_get_contents('php://input');
        $check_res = $Wxpay->checkSign($inWechatpaySignature,$inWechatpayTimestamp,$inWechatpayNonce,$inBody);
        //$check_res['out_trade_no'] = 'A2023062949975452';
        if($check_res)
        {
            Db::startTrans();
            try{
                $out_trade_no = $check_res['out_trade_no'];
                $order_info = AgentOrderModel::where('out_trade_no',$out_trade_no)->find();
                if(!$order_info)
                {
                    $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
                    return $str;
                }
                if($order_info['status'] == 1)
                {
                    $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    return $str;
                }
                $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
                
                $order_data['status'] = '1';
                $order_data['pay_time'] = time();
                $status = AgentOrderModel::where('out_trade_no',$out_trade_no)->update($order_data);
                if($status === false)
                {
                    Db::rollback();
                    
                    echo $str;die;
                }
                $user_info = UserModel::where('id',$order_info['user_id'])->find();
                if(!$user_info)
                {
                    Db::rollback();
                    
                    echo $str;die;
                }
                $user_data['is_agent'] = 1;
                $user_data['username'] = $order_info['username'];
                $user_data['password'] = $this->getEncryptPassword($order_info['password'], $user_info['salt']);
                $u_status = UserModel::where('id',$order_info['user_id'])->update($user_data);
                if($u_status === false)
                {
                    Db::rollback();
                    
                    echo $str;die;
                }
                if($order_info['zt_user_id'] )
                {
                    $zh_user_info = UserModel::where('id',$order_info['zt_user_id'])->find();
                    if($zh_user_info)
                    {
                        //绑定关系
                        $agent_los = [
                            'user_id'=>$order_info['user_id'],
                            'agent_id'=>$order_info['zt_user_id'],
                            'tagent_id'=>$order_info['jt_user_id'],
                            'createtime'=>time(),
                        ];
                        $status1 = AgentLogModel::insertGetId($agent_los);
                        if(!$status1)
                        {
                            Db::rollback();
                        
                            echo $str;die;
                        }
                        if($order_info['zt_money'])
                        {
                            //发放奖励
                            $zt_user_data['money'] = $zh_user_info['money'] + $order_info['zt_money'];
                            $zt_user_data['total_money'] = $zh_user_info['total_money'] + $order_info['zt_money'];
                            $u_status = UserModel::where('id',$order_info['zt_user_id'])->update($zt_user_data);
                            if($status1 === false)
                            {
                                Db::rollback();
                            
                                echo $str;die;
                            }
                            //插入奖励日志
                            $log = [
                                'user_id'=>$order_info['user_id'],
                                'agent_id'=>$order_info['zt_user_id'],
                                'money'=>$order_info['zt_money'],
                                'memo'=>'推荐成为代理',
                                'order_id'=>$order_info['id'],
                                'createtime'=>time(),
                                'type'=>2,
                                'status'=>'2'
                            ];
                            RewardLogModel::insertGetId($log);
                        }
                        
                    }
                    
                    
                }
                if($order_info['jt_user_id'])
                {
                    $zh_user_info = UserModel::where('id',$order_info['jt_user_id'])->find();
                    if($zh_user_info)
                    {
                        if($order_info['jt_money'])
                        {
                            //发放奖励
                            $zt_user_data['money'] = $zh_user_info['money'] + $order_info['jt_money'];
                            $zt_user_data['total_money'] = $zh_user_info['total_money'] + $order_info['jt_money'];
                            $u_status = UserModel::where('id',$order_info['jt_user_id'])->update($zt_user_data);
                            if($status1 === false)
                            {
                                Db::rollback();
                            
                                echo $str;die;
                            }
                            //插入奖励日志
                            $log = [
                                'user_id'=>$order_info['user_id'],
                                'agent_id'=>$order_info['jt_user_id'],
                                'money'=>$order_info['jt_money'],
                                'memo'=>'推荐成为代理',
                                'order_id'=>$order_info['id'],
                                'createtime'=>time(),
                                'level'=>2,
                                'type'=>2,
                                'status'=>'2'
                            ];
                            RewardLogModel::insertGetId($log);
                        }
                        
                    }
                }
                Db::commit();
                $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                return $str; 
            }catch(Expection $e)
            {
                Db::rollback();
            }
            
            
            
            
            $str = '<xml><return_code><![CDATA[FAIL3]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
            return $str;
        }
    }
        
     /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
    
}
